<!-- 参考文档: https://blog.csdn.net/weixin_42623929/article/details/122864736-->
<template>
    <div class="xj-layer-box">
        <avue-form v-if="initSuccess" ref="form" v-model="obj" :option="option"
                   @reset-change="emptytChange"
                   @submit="submit">
            <template v-if="obj.type === 0" #content="scope">
                <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入内容"
                    v-model="obj.content">
                </el-input>
            </template>
            <template v-if="obj.type === 2" #content="scope">
                <el-switch
                    v-model="obj.content"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    active-value="true"
                    inactive-value="false">
                </el-switch>
            </template>
            <template v-if="obj.type === 3" #content="scope">
                <TinymceEditor :content.sync="obj.content" @update:content="obj.content = $event"/>
            </template>
            <template v-if="obj.type === 4" #content="scope">
                <MdEditor :content.sync="obj.content" @update:content="obj.content = $event"></MdEditor>
            </template>
            <template v-if="obj.type === 5" #content="scope">
                <JsonEditor v-model="obj.content"/>
            </template>
        </avue-form>
    </div>
</template>

<script>
import {uploadPath} from "@/config/env";
import {ElMessage} from "element-plus";
import JsonEditor from '@/components/json-editor/json-editor.vue';

export default {
    components: {
        JsonEditor,
    },
    data() {
        return {
            obj: {},
            isIdFind: true,
            initSuccess: false,
            fileList: [],
            treeData: [],
            uploadPath: uploadPath,
            toolbar: {
                addDefaultJson: {
                    title: '+ 默认值',
                    text: '+ 默认值',
                    action(editor) {
                        editor.insert(function (selected) {
                            return {
                                text: '{\n  "title": "标题",\n  "content": "这是一段内容"\n}',
                                selected: selected,
                            };
                        });
                    },
                },
            }
        }
    },
    props: {
        closeDialog: [],
        uri: {},
        rowData: {},
    },
    computed: {
        option() {
            return {
                // size: "small",
                submitBtn: true,
                emptyBtn: true,
                submitText: '提交',
                emptyText: "关闭",
                column: [
                    {
                        label: '类型',
                        prop: 'type',
                        type: 'radio',
                        disabled: true,
                        dicData: this.dict.get(this.website.Dict.Base.ConfigType),
                        span: 20,
                        rules: [{
                            required: true,
                            message: "请选择 类型",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '父级',
                        prop: 'pid',
                        type: 'tree',
                        span: 20,
                        display: true,
                        dicData: this.treeData,
                        props: {
                            value: "id",
                            label: "name",
                            children: "children"
                        },
                        rules: [{
                            required: true,
                            message: "请选择 父id",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '配置code',
                        prop: 'code',
                        maxlength: 32,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: true,
                            message: "请输入 配置code|搜索值",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '配置名称',
                        prop: 'name',
                        maxlength: 32,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: true,
                            message: "请输入 配置名称",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '配置内容',
                        prop: 'content',
                        type: 'textarea',
                        display: this.obj.type !== 1,
                        maxlength: 0,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: true,
                            message: "请输入 配置内容",
                            trigger: "blur"
                        }]
                    },
                    {
                        // 配置内容为图片时, 使用此字段
                        label: '图片',
                        prop: 'content',
                        dataType: 'string',
                        display: this.obj.type === 1,
                        // labelWidth: 110,
                        rules: [{
                            required: true,
                            message: "请上传 配置图片 ",
                            trigger: "blur"
                        }],
                        span: 24,
                        accept: 'image/png, image/jpeg, image/jpg, image/gif',
                        type: 'upload',
                        listType: 'picture-card',
                        action: uploadPath,      // 上传地址 + 文件保存上传地址(详见接口描叙)
                        multiple: true,          // 文件多选
                        drag: true,            // 拖拽排序
                        limit: 10,             // 上传数量 10 个
                        //fileSize: 500,         // 上传大小 500 kb内
                        tip: '只能上传10张 jpg/jpeg/png/gif 格式的图片',
                        loadText: '上传中...',
                        propsHttp: {
                            res: 'data'
                        },
                        uploadBefore: (file, done) => {
                            // 文件上传前处理
                            done(file)
                        },
                        uploadAfter: (res, done) => {
                            // this.$message.success('上传成功');
                            done()
                        },
                        uploadError(error, column) {
                            // 上传失败
                            this.$message.error(error);
                        },
                        uploadExceed(limit, files, fileList, column) {
                            // 文件数量验证
                            this.$message.warning(`当前限制文件数量为 $10, 当前共 ${files.length + fileList.length} `);
                        },
                    },
                    {
                        label: '排序',
                        prop: 'sort',
                        type: 'number',
                        minRows: 0,
                        maxRows: 99999999,
                        row: true,
                        span: 20,
                        rules: [{
                            required: true,
                            message: "请输入 排序",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '描述',
                        prop: 'desc',
                        maxlength: 1024,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: false,
                            message: "请输入 描述",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: '扩展字段1',
                        prop: 'ext1',
                        maxlength: 128,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: false,
                            message: " 扩展字段1",
                            trigger: "blur"
                        }]
                    }, {
                        label: '扩展字段2',
                        prop: 'ext2',
                        maxlength: 128,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: false,
                            message: " 扩展字段2",
                            trigger: "blur"
                        }]
                    }, {
                        label: '扩展字段3',
                        prop: 'ext3',
                        maxlength: 128,
                        showWordLimit: true,
                        span: 20,
                        rules: [{
                            required: false,
                            message: " 扩展字段3",
                            trigger: "blur"
                        }]
                    },
                ]
            }
        }
    },
    async created() {
        if (this.isIdFind) {
            await this.findId(this.rowData);
        } else {
            this.obj = this.rowData;
        }
        // 处理父级数据
        this.treeData = JSON.parse(JSON.stringify(this.rowData.pidDic));
        this.treeDisabledHandle(this.treeData, this.rowData.id);
        this.initSuccess = true;
    },
    methods: {
        emptytChange() {
            this.$emit('closeDialog', false);
        },
        // 递归处理自己 + 自己的下级ids 不能选
        treeDisabledHandle(children, id) {
            if (children == null) {
                return
            }
            for (let i = 0; i < children.length; i++) {
                if (children[i].pid === id || children[i].id === id) {
                    children[i].disabled = true;
                    this.treeDisabledHandle(children[i].children, children[i].id)
                } else {
                    this.treeDisabledHandle(children[i].children, id);
                }
            }
        },
        submit(form, done) {
            // 数据验证
            if (this.obj.type === 5 && !this.isValidJson(this.obj.content)) {
                ElMessage({message: "配置内容 JSON 格式错误", type: 'error'});
                done(form);
                return Promise.reject(new Error("配置内容 JSON 格式错误"))
            }

            this.crud.put(this.uri.info + "/" + this.obj.id, this.obj).then((res) => {
                if (res.data.code == 200) {
                    this.$emit('closeDialog', true, this.obj.id);
                }
                done(form);
            }).catch(err => {
                console.error(err);
                done(form);
            })
        },
        async findId(newRowData) {
            if (newRowData != null && newRowData.id != null) {
                let res = await this.crud.get(this.uri.info + "/" + newRowData.id);
                Object.assign(this.obj, res.data.data);
            }
        },
        isValidJson(jsonStr) {
            try {
                JSON.parse(jsonStr);
                return true;
            } catch (error) {
                return false;
            }
        }
    }
}
</script>
